<template>
  <div id="User-container">
    <!-- 导航头 -->
    <van-nav-bar class="page-nav-bar" title="个人信息" left-arrow @click-left="$router.back()" />
    <!-- /导航栏 -->
    <input type="file" ref="inputFile" hidden @change="onChange" />
    <van-cell title="头像" is-link @click="$refs.inputFile.click()">
      <van-image class="avatar" fit="cover" round :src="user.photo" />
    </van-cell>
    <van-cell title="昵称" :value="user.name" is-link @click="show = true" />
    <van-cell title="性别" :value="user.gender ? '女' : '男'" is-link @click="showSex = true" />
    <van-cell title="生日" :value="user.birthday" is-link @click="showBirday = true" />

    <!-- 编辑昵称弹出框 -->
    <van-popup v-model="show" position="bottom" :style="{ height: '100%' }">
      <user-edit @close="show = false" v-model="user.name" @input="user.name = $event" />
    </van-popup>

    <!-- 编辑性别出框 -->
    <van-popup v-model="showSex" position="bottom" :style="{ height: '50%' }">
      <user-edit-sex @close="showSex = false" v-model="user.gender" @input="user.genfer = $event" />
    </van-popup>

    <!-- 编辑生日出框 -->
    <van-popup v-model="showBirday" position="bottom" :style="{ height: '50%' }">
      <user-birday @close="showBirday = false" v-model="user.birthday" @input="user.birthday = $event" />
    </van-popup>

    <!-- 编辑头像出框 -->
    <van-popup v-model="showPhoto" position="bottom" :style="{ height: '100%' }">
      <user-avatar :img="imgUrl" @close="showPhoto = false" @update-avatar="user.photo = $event" v-if="showPhoto" />
    </van-popup>
  </div>
</template>

<script>
import { Toast } from 'vant'
import { getUserProfile } from '@/api/user.js'
import userEdit from './components/userEdit.vue'
import userEditSex from './components/userEditSex.vue'
import userBirday from './components/userBirday.vue'
import userAvatar from './components/userAvatar.vue'

export default {
  name: 'User',
  data () {
    return {
      user: {},
      show: false,
      showSex: false,
      showBirday: false,
      showPhoto: false,
      imgUrl: ''
    }
  },
  components: {
    userEdit,
    userEditSex,
    userBirday,
    userAvatar
  },
  created () {
    this.loadUserProfile()
  },
  methods: {
    async loadUserProfile () {
      try {
        const res = await getUserProfile()
        // console.log(res)
        this.user = res
      } catch (err) {
        Toast.fail('获取用户个人资料失败')
      }
    },
    onChange (e) {
      if (e.target.value === '') return
      this.showPhoto = true
      this.imgUrl = URL.createObjectURL(e.target.files[0])
      e.target.value = ''
    }
  }
}
</script>

<style lang='less' scoped>
#User-container {
  .avatar {
    width: 60px;
    height: 60px;
  }
  /deep/.van-nav-bar__arrow {
    color: #fff;
  }
}
</style>
